import { useState } from 'react'

//数组变对象
const arr = [['name', 'a三'], ['age', 28]]
const obj = new Map(arr)
console.log(Object.fromEntries(obj))
const App = () => {
    //修改值的方法
    const setState = ({ target }, index) => {
        console.log(target.name)
        if (target.name === 'arr') {
            const _arr = [...arr]
            const index = _arr.findIndex(value =>
                value.includes("赵"))
            if (index !== -1) {
                _arr.splice(index, 1, '王')
                setArr(_arr)
            } else {
                alert("没找到你要修改的字")
            }

        } else if (target.name === 'person') {
            const _person = { ...person }
            _person.age = 25;
            _person.job = 'web前端'
            setperson(_person)
        } else if (target.name === 'book') {
            const _book = [...book]
            const money = parseInt(_book[index].money)
            console.log(money)
            _book[index].money = money + 100 + '元'
            setBook(_book)
        }
    }
    //数组
    const [arr, setArr] = useState(['张', '李', '赵', '刘'])
    //对象
    const [person, setperson] = useState(
        { name: '老开', age: 80, job: '退休' }
    )
    //数组对象
    const [book, setBook] = useState(
        [
            { book: '北京那些事', money: "$15" },
            { book: '时间简史(盗版)', money: "$20" },
            { book: 'c++从入门到放弃', money: "$100+" }
        ]
    )
    return <div>
        {   //arr=[];arr.map()
            // function 相对map来说就是回调函数
            arr.map(function (value, index, orgin) {
                return <span key={index}>{value}{index === orgin.length - 1 ? '.' : ","}</span>
            })
        }
        <button name='arr' onClick={setState}>赵变王</button>
        <br />
        {   //对象变数组
            //map是数组方法,对象要用首先应该对象转数组,方法 Object.entries(obj)
            Object.entries(person).map(function (arr, index) {
                return <p key={index}>
                    {`${arr[0]}:${arr[1]}`}
                </p>
            })
        }
        <button name='person' onClick={setState}>修改年龄和退休,回到25</button>
        <br />
        {
            book.map((item, index) => {
                return <h1 key={index}>
                    <mark>{item.book}</mark>
                    <span style={{ backgroundColor: 'red' }}>{item.money}</span>
                    <button name='book' onClick={(event) => setState(event, index)}>修改单价+100</button>
                </h1>
            })
        }
    </div>
}

export default App
